package com.zy.je.common.core.utils;

import org.dromara.hutool.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ToStringJsonParser {

    private static final Pattern NESTED_OBJECT_PATTERN = Pattern.compile("^([A-Za-z0-9_]+)\\s*\\((.*)\\)$");

    public static JSONObject parse(String toStringResult) {
        int firstParen = toStringResult.indexOf('(');
        int lastParen = toStringResult.lastIndexOf(')');
        if (firstParen != -1 && lastParen != -1 && firstParen < lastParen) {
            String content = toStringResult.substring(firstParen + 1, lastParen);
            return parseRecursive(content);
        } else {
            return new JSONObject();
        }
    }

    private static JSONObject parseRecursive(String str) {
        JSONObject jsonObject = new JSONObject();
        StringBuilder currentKey = new StringBuilder();
        StringBuilder currentValue = new StringBuilder();
        int bracketLevel = 0;
        boolean isParsingValue = false;

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            if (c == '(') {
                bracketLevel++;
            } else if (c == ')') {
                bracketLevel--;
            }

            if (c == ',' && bracketLevel == 0) {
                processEntry(jsonObject, currentKey.toString().trim(), currentValue.toString().trim());
                currentKey.setLength(0);
                currentValue.setLength(0);
                isParsingValue = false;
                continue;
            }

            if (c == '=' && bracketLevel == 0) {
                isParsingValue = true;
                continue;
            }

            if (!isParsingValue) {
                currentKey.append(c);
            } else {
                currentValue.append(c);
            }
        }

        // 处理最后一个键值对
        processEntry(jsonObject, currentKey.toString().trim(), currentValue.toString().trim());

        return jsonObject;
    }

    private static void processEntry(JSONObject jsonObject, String key, String valueStr) {
        if (key.isEmpty()) {
            return;
        }

        valueStr = valueStr.trim();
        Object processedValue = parseValue(valueStr);
        jsonObject.putValue(key, processedValue);
    }

    private static Object parseValue(String valueStr) {
        // 处理嵌套对象
        Matcher matcher = NESTED_OBJECT_PATTERN.matcher(valueStr);
        if (matcher.matches()) {
            String content = matcher.group(2).trim();
            // 确保内容的括号层级正确
            if (content.endsWith(")")) {
                content = removeOuterWrapperParentheses(content);
            }
            return parseRecursive(content);
        }

        // 处理字符串（带单引号）
        if (valueStr.startsWith("'") && valueStr.endsWith("'") && valueStr.length() >= 2) {
            return valueStr.substring(1, valueStr.length() - 1);
        }

        // 处理数值类型
        try {
            if (valueStr.contains(".")) {
                return Double.parseDouble(valueStr);
            } else {
                return Integer.parseInt(valueStr);
            }
        } catch (NumberFormatException e) {
            // 非数字，返回原始字符串
            return valueStr;
        }
    }

    private static String removeOuterWrapperParentheses(String content) {
        int firstParen = content.indexOf('(');
        int lastParen = content.lastIndexOf(')');
        if (firstParen != -1 && lastParen != -1 && firstParen < lastParen) {
            return content.substring(firstParen + 1, lastParen);
        }
        return content;
    }

    public static void main(String[] args) {
        String example = "Person(name='John', age=30, address=Address(city='New York', street='Wall Street', location=Location(latitude=40.7128, longitude=-74.0060)))";
        JSONObject json = parse(example);
        System.out.println(json);
    }
}
